/**
 * 
 */
package json;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * @author Beanstao@gmail.com
 * @date 2013-10-27
 * @version 1.0
 */
public class JacksonHelperTest
{

	public static void main(String[] args) throws Exception
	{
		test1();

		getValue(genTestVo());
	}

	/**
	 * 简单的bean-json之间的转化
	 */
	public static void test1() throws Exception
	{
		TestVo vo = genTestVo();

		// 实体转JSON字符串
		String json = JacksonHelper.beanToJson(vo);
		System.out.println("Bean>>>Json----" + json);
		// 字符串转实体
		TestVo vo2 = (TestVo) JacksonHelper.jsonToBean(json, TestVo.class);
		System.out.println("Json>>>Bean----与开始的对象是否相等：" + vo2.equals(vo));

		System.out.println();
	}

	public static void getValue(TestVo vo) throws Exception
	{
		String voJson = JacksonHelper.beanToJson(vo);
		// 这里的JsonNode和XML里面的Node很像
		JsonNode node = JacksonHelper.getObjectMapper(false).readTree(voJson);

		System.out.println("读取json字符串中对象的属性值>>>" + node.get("voName").toString());
		System.out.println();

		node = node.get("pers");
		System.out.println("node是不是个集合：" + node.isArray());
		for (int i = 0; i < node.size(); i++)
		{
			JsonNode childNode = node.get(i);
			System.out.println("读取json字符串中数组对象的属性值>>>" + childNode.get("name").toString());
		}
		System.out.println();

		String json = JacksonHelper.beanToJson(genTestVoWithChilds());
		Object[] obj = JacksonHelper.readValueFromJson(json, "pers:childs:name").toArray();
		System.out.println(Arrays.toString(obj));
		System.out.println();

		String voJson2 = JacksonHelper.beanToJson(genTestVoWithChilds());
		JsonNode node2 = JacksonHelper.getObjectMapper(false).readTree(voJson2);
		JacksonHelper.getValueByFind(node2, "age");
		JacksonHelper.getFirstValueByFind(node2, "age");
		System.out.println();

		System.out.println();

	}

	/**
	 * 提供测试数据：生成一个TestVo。
	 */
	private static TestVo genTestVo()
	{
		List<Person> pers = new ArrayList<Person>();

		Person p = new Person("张三", 46);
		pers.add(p);
		p = new Person("李四", 19);
		pers.add(p);
		p = new Person("王二麻子", 23);
		pers.add(p);
		return new TestVo("一个容器而已", pers);
	}

	/*
	 * 提供测试数据：生成带有childs属性的Person的TestVo。
	 */
	private static TestVo genTestVoWithChilds()
	{
		List<Person> pers = new ArrayList<Person>();
		List<Person> childs = new ArrayList<Person>();

		Person p = new Person("张三", 46);
		childs.add(new Person("小张三1", 20));
		childs.add(new Person("小张三2", 17));
		p.setChilds(childs);
		pers.add(p);

		p = new Person("李四", 29);
		childs = new ArrayList<Person>();
		childs.add(new Person("小李四1", 20));
		p.setChilds(childs);
		pers.add(p);

		p = new Person("王二麻子", 23);
		pers.add(p);

		return new TestVo("一个容器而已", pers);
	}
}
